package com.vecspace.utils.datetime;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

import java.io.IOException;
import java.time.*;
import java.time.format.DateTimeFormatter;

public class MyLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
    DateTimeFormatter dtfDate = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    DateTimeFormatter dtfDateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    DateTimeFormatter dtfDateTimeMills = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
    @Override
    public LocalDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException {
        String dateStr = parser.getText().trim();
        if (dateStr.length() == 0) {
            return null;
        }
        int tIdx = dateStr.indexOf("T");
        if(tIdx > 0){
            if(dateStr.indexOf("+", tIdx) > 0 || dateStr.indexOf("-", tIdx) > 0 || dateStr.endsWith("Z")){//包含时区 "2015-08-18T06:00:01+09:00" "2015-08-18T06:00:01.001+09:00"
                ZonedDateTime zonedDateTime = ZonedDateTime.parse(dateStr);
                LocalDateTime localDateTime = zonedDateTime.withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime();//本地时区必须和数据库时区设置为一致。
                return localDateTime;
            }else{//不包含时区 2015-08-18T06:00:01 2015-08-18T06:00:01.121
                LocalDateTime localDateTime = LocalDateTime.parse(dateStr);
                return localDateTime;
            }
        }else{
            if(dateStr.indexOf("-")>0) {//不能等于0，因为dateStr可能是一个Unix时间戳(毫秒)，可能为负数。
                int len = dateStr.length();
                if (10 == len) {//yyyy-MM-dd
                    LocalDate localDate = LocalDate.parse(dateStr, dtfDate);
                    LocalDateTime localDateTime = localDate.atTime(0,0,0);
                    return localDateTime;
                } else if (19 == len) {//yyyy-MM-dd HH:mm:ss
                    LocalDateTime localDateTime = LocalDateTime.parse(dateStr, dtfDateTime);
                    return localDateTime;
                } else if (23 == len) {//yyyy-MM-dd HH:mm:ss
                    LocalDateTime localDateTime = LocalDateTime.parse(dateStr, dtfDateTimeMills);
                    return localDateTime;
                }else{
                    return null;
                }
            }else{//dateStr可能是一个Unix时间戳(毫秒)
                long mills = Long.parseLong(dateStr);
                LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(mills), ZoneId.systemDefault());
                return localDateTime;
            }
        }
    }
}

